package co.fitstart.scheduler.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.DateUtils;

import co.fitstart.scheduler.Constant;
import co.fitstart.scheduler.persistence.GenericJdbcSupport;
import co.fitstart.scheduler.service.OrderService;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private GenericJdbcSupport genericJdbcSupport;

    /*
     * (non-Javadoc)
     * @see co.fitstart.scheduler.service.OrderService#toCloseOnlineOrder(java.util.Date)
     */
    public int toCloseOnlineOrder(Date now) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("created", Constant.ORDER_STATUS_CREATED);
        parameters.put("unpaid", Constant.PAYMENT_STATUS_UNPAID);
        parameters.put("online", Constant.COUSER_TYPE_ONLINE);
        parameters.put("online", Constant.COUSER_TYPE_ONLINE);
        parameters.put("time", DateUtils.addDays(now, -2));
        return genericJdbcSupport.queryForInt("SELECT COUNT(*) FROM orders"
                + " WHERE is_disabled=false AND order_status = :created AND payment_status = :unpaid"
                + " AND order_type = :online AND create_time < :time", parameters);
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.scheduler.service.OrderService#closeOnlineOrder(java.util.Date)
     */
    public void closeOnlineOrder(Date now) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", Constant.ORDER_CLOSE_TIME);
        parameters.put("value", DateFormatUtils.format(now, "yyyy-MM-dd HH:mm:ss"));
        parameters.put("orderStatus", Constant.ORDER_STATUS_CANCELED);
        parameters.put("paymentStatus", Constant.PAYMENT_STATUS_CANCELED);
        parameters.put("created", Constant.ORDER_STATUS_CREATED);
        parameters.put("unpaid", Constant.PAYMENT_STATUS_UNPAID);
        parameters.put("online", Constant.COUSER_TYPE_ONLINE);
        parameters.put("time", DateUtils.addDays(now, -2));
        
        genericJdbcSupport.executeSQL("INSERT INTO order_attr(name,value,order_id)"
                + " SELECT :name,:value,id FROM orders"
                + " WHERE is_disabled=false AND order_status = :created"
                + " AND order_type = :online AND create_time < :time", parameters);
        
        genericJdbcSupport.executeSQL("UPDATE orders SET order_status = :orderStatus,payment_status = :paymentStatus"
                + " WHERE is_disabled=false AND order_status = :created AND payment_status = :unpaid"
                + " AND order_type = :online AND create_time < :time", parameters);
    }

}
